public class Test_8_24 {

    //力扣：206. 反转链表
    public ListNode reverseList(ListNode head) {
        if(head == null) {
            return null;
        }
        ListNode cur = head.next;
        head.next = null;
        while(cur != null) {
            ListNode curNext = cur.next;
            cur.next = head;
            head = cur;
            cur= curNext;
        }
        return head;
    }


    //力扣：876. 链表的中间结点
    public ListNode middleNode(ListNode head) {
        if(head == null) return null;
        if(head.next == null) return head;
        if(head.next.next == null) return head.next;
        ListNode fast = head;
        ListNode slow = head;
        while(fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;

    }


    //牛客网：链表中倒数第k个结点
    public ListNode FindKthToTail(ListNode head,int k) {
        if(head == null || k <= 0) return null;

        ListNode slow = head;
        ListNode fast = head;
        for(int i = k-1; i > 0; i--) {
            fast = fast.next;
            if(fast == null) {
                return null;
            }
        }
        while(fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }


    //力扣：21. 合并两个有序链表
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if(list1 == null) return list2;
        if(list2 == null) return list1;


        ListNode head = new ListNode();
        ListNode lastNode = head;

        while(list1 != null && list2 != null) {
            if(list1.val < list2.val) {
                lastNode.next = list1;
                list1 = list1.next;
            }else {
                lastNode.next = list2;
                list2 = list2.next;
            }
            lastNode = lastNode.next;
        }
        if(list1 == null) lastNode.next = list2;
        if(list2 == null) lastNode.next = list1;
        return head.next;
    }
}
